import { BASE_API } from "@/config";
import { getUserInfo } from "@/service";

let stateBarHeight = ref(0);
let headerHeight = ref(50);
let windowWidth = ref(0);

const getStateBarHeight = () => {
  let info = uni.getSystemInfoSync();
  stateBarHeight = info.statusBarHeight;
  windowWidth = info.windowWidth;
  return stateBarHeight;
};
const getMenuButtonInfo = () => {
  // #ifdef MP-WEIXIN
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
  let paddingSize = menuButtonInfo.top - stateBarHeight;
  headerHeight = menuButtonInfo.bottom - stateBarHeight + paddingSize;
  windowWidth = menuButtonInfo.left - 24;
  // #endif
  return {
    headerHeight,
    windowWidth
  }
};

function uploadFile(filePath) {
  const userInfo = getUserInfo();
  uni.showLoading({
    title: "正在上传...",
    icon: "loading"
  });
  return new Promise(function (resolve, reject) {
    uni.uploadFile({
      url: `${BASE_API}/common/upload`,
      filePath,
      name: "file",
      header: {
        token: userInfo.token
      },
      success: (res) => {
        uni.hideLoading();
        uni.showToast({
          title: "上传成功",
          icon: "success",
          mask: true
        });
        resolve(JSON.parse(res.data).data.url);
      },
      fail: (err) => {
        uni.hideLoading();
        uni.showToast({
          title: "上传失败",
          icon: "error",
          mask: true
        });
        reject(err);
      }
    });
  });
}

export function dateFormat(date, fmt) {
  console.log(date, fmt);
  let ret;
  const opt = {
    "Y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "H+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "S+": date.getSeconds().toString() // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0"));
    }
  }
  return fmt;
}

function formatTimeNum(num) {
  return num >= 10 ? num : "0" + num;
}
export function formatDate(timestamp, format) {
  if (isNaN(Number(timestamp))) {
    return "- -";
  } else {
    var now = new Date(timestamp);
    var year = formatTimeNum(now.getFullYear());
    var month = formatTimeNum(now.getMonth() + 1);
    var date = formatTimeNum(now.getDate());
    var hour = formatTimeNum(now.getHours());
    var minute = formatTimeNum(now.getMinutes());
    var second = formatTimeNum(now.getSeconds());
    if (!format) {
      return year + "-" + month + "-" + date;
    } else if (format == "ym") {
      return year + "-" + month;
    } else if (format == "zh-ym") {
        return year + "年" + month+'月';
      } else if (format == "ms") {
      return hour + ":" + minute + ":" + second;
    } else if (format == "md") {
      return month + "-" + date;
    }
  }
}

const compareVersion = (v1, v2)=>{
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len)
    v1.push('0')

  while (v2.length < len)
    v2.push('0')

  for (let i = 0; i < len; i++) {
    const num1 = Number.parseInt(v1[i])
    const num2 = Number.parseInt(v2[i])

    if (num1 > num2)
      return 1

    else if (num1 < num2)
      return -1
  }
  return 0
}

const shareService = {
  onShareAppMessage: function () {
    return {
      title: "xxx",
      desc: "xxxxx"
    };
  }
};

// 复制内容到剪贴板
const copyContent = (data) => {
  uni.setClipboardData({
    data,
    success: function () {
      uni.showToast({
        title: "复制成功",
        icon: "success",
        mask: true
      });
    }
  });
};

// 下载文件(流文件)
const downloadFileBlob = (res, filename) => {
  const href = window.URL.createObjectURL(res);
  const a = document.createElement("a");
  a.href = href;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  //
  document.body.removeChild(a);
};

// 下载文件(url地址)
const downloadFileUrl = (res, filename) => {
  const href = res;
  const a = document.createElement("a");
  a.style.display = "none";
  a.href = href;
  a.download = filename;
  a.target = "_self"; // 本地窗口打开链接
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

// 下载文件(url地址)新窗口
const downloadFileUrlNew = (res, filename) => {
  const href = res;
  const a = document.createElement("a");
  a.style.display = "none";
  a.href = href;
  a.download = filename;
  a.target = "_blank"; // 新窗口打开链接
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

// 图片转成base64格式
const  base64src = (data)=> {
  /// 获取到base64Data
  var base64Data = data;
  /// 通过微信小程序自带方法将base64转为二进制去除特殊符号，再转回base64
  base64Data = wx.arrayBufferToBase64(wx.base64ToArrayBuffer(base64Data));
  /// 拼接请求头，data格式可以为image/png或者image/jpeg等，看需求
  const base64ImgUrl = "data:image/png;base64," + base64Data;
  /// 刷新数据
  return base64ImgUrl;
}

const getQueryParam = (url, name) => {
  console.log("url = " + url);
  console.log("name = " + name);
  var reg = new RegExp("(^|&|/?)" + name + "=([^&|/?]*)(&|/?|$)", "i");
  var r = url.substr(1).match(reg);
  if (r != null) {
    console.log("r = " + r);
    console.log("r[2] = " + r[2]);
    return r[2];
  }
  return null;
};

const _superantUtils = {
  shareService,
  copyContent,
  compareVersion,
  uploadFile,
  downloadFileBlob,
  downloadFileUrl,
  downloadFileUrlNew,
  base64src,
  getQueryParam,
  getStateBarHeight,
  getMenuButtonInfo
};



export default _superantUtils;


